/*
 * Copyright (c) 2022 86188
 * Licensed under the Open Software Licence, Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://opensource.org/licenses/osl-3.0.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bei.lingluan.slice;

import com.bei.lingluan.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.Text;
import ohos.agp.components.webengine.*;
import ohos.agp.utils.TextTool;
import ohos.agp.window.service.WindowManager;
import ohos.global.resource.Resource;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.net.Uri;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;

/**
 * @author 北海
 * @version 1.0
 * @date 2022/7/27
 */
public class WebViewSlice extends AbilitySlice {

    private final HiLogLabel TAG = new HiLogLabel(HiLog.LOG_APP, 0x02, WebViewSlice.class.getName());
    private String localUrl;
    private WebView mWebContent;
    private Text mTitle;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_silce_webview);
        localUrl = intent.getStringParam("fileName");

    }


    @Override
    protected void onActive() {
        super.onActive();
        getWindow().clearFlags(WindowManager.LayoutConfig.MARK_TRANSLUCENT_NAVIGATION);
        mTitle = findComponentById(ResourceTable.Id_titleBar_title);
        initBackBtn();
        initWebView();
        loadLocalFileConfig();
        browseObserve();
        mWebContent.load("https://bei.com/rawfile/" + localUrl);
    }

    /**
     * 初始化返回按钮
     */
    private void initBackBtn() {
        Button back = findComponentById(ResourceTable.Id_titleBar_back);
        back.setClickedListener(component -> terminate());
    }

    /**
     * 绑定组件
     */
    private void initWebView() {
        DependentLayout dLayout = findComponentById(ResourceTable.Id_webView_content_layout);
        mWebContent = new WebView(getContext());
        mWebContent.setWidth(ComponentContainer.LayoutConfig.MATCH_PARENT);
        mWebContent.setHeight(ComponentContainer.LayoutConfig.MATCH_PARENT);
        mWebContent.getWebConfig().setJavaScriptPermit(true);
        dLayout.addComponent(mWebContent);
    }

    /**
     * 加载本地资源
     */
    private void loadLocalFileConfig() {
        mWebContent.setWebAgent(new WebAgent() {
            @Override
            public ResourceResponse processResourceRequest(WebView webview, ResourceRequest request) {
                final String authority = "bei.com";
                final String rawFile = "/rawfile/";
                final String local = "/local/";
                Uri requestUri = request.getRequestUrl();
                if (authority.equals(requestUri.getDecodedAuthority())) {
                    String path = requestUri.getDecodedPath();
                    if (TextTool.isNullOrEmpty(path)) {
                        return super.processResourceRequest(webview, request);
                    }
                    if (path.startsWith(rawFile)) {
                        // 根据自定义规则访问资源文件
                        String rawFilePath = "entry/resources/rawfile/" + path.replace(rawFile, "");
                        String mimeType = URLConnection.guessContentTypeFromName(rawFilePath);
                        try {
                            Resource resource = getResourceManager().getRawFileEntry(rawFilePath).openRawFile();
                            return new ResourceResponse(mimeType, resource, null);
                        } catch (IOException e) {
                            HiLog.error(TAG, "open raw file failed");
                        }
                    }
                    if (path.startsWith(local)) {
                        // 根据自定义规则访问本地文件
                        String localFile = getContext().getFilesDir() + path.replace(local, "/");
                        File file = new File(localFile);
                        if (!file.exists()) {
                            HiLog.error(TAG, "file not exists");
                            return super.processResourceRequest(webview, request);
                        }
                        String mimeType = URLConnection.guessContentTypeFromName(localFile);
                        try {
                            InputStream inputStream = new FileInputStream(file);
                            return new ResourceResponse(mimeType, inputStream, null);
                        } catch (IOException e) {
                            HiLog.error(TAG, "open local file failed");
                        }
                    }
                }
                return super.processResourceRequest(webview, request);
            }
        });
    }

    /**
     * 观测浏览事件
     */
    private void browseObserve() {
        mWebContent.setBrowserAgent(new BrowserAgent(this) {
            @Override
            public void onTitleUpdated(WebView webview, String title) {
                super.onTitleUpdated(webview, title);
                // 标题变更时处理
                mTitle.setText(title);
            }
        });
    }
}
